<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-dialog width="30%" title="内层 Dialog" :visible.sync="innerVisible" append-to-body></el-dialog>

    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <el-form-item label="消息类型" prop="type">
        <el-select v-model="dataForm.type">
          <el-option key="1" label="公共消息" value="1"></el-option>
          <el-option key="2" label="指定用户消息" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="消息标题" prop="title">
        <el-input v-model="dataForm.title" placeholder="消息标题"></el-input>
      </el-form-item>
      <el-form-item label="消息内容" prop="content">
        <el-upload
          id="upimg"
          v-show="false"
          class="upload-demo"
          :action="imgUploadUrl"
          :on-success="handleSuccess"
          :headers="config"
          multiple
        >
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>

        <quill-editor v-model="dataForm.content" :options="editorOption" ref="QuillEditor"></quill-editor>
      </el-form-item>

      <el-form-item label="业务状态" prop="status">
        <el-select v-model="dataForm.status">
          <el-option key="0" label="不可见" value="0"></el-option>
          <el-option key="1" label="可见" value="1"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="创建时间" prop="createDate">
        <el-input v-model="dataForm.createDate" placeholder="创建时间"></el-input>
      </el-form-item>

      <el-form-item label="更新时间" prop="updateDate">
        <el-input v-model="dataForm.updateDate" placeholder="更新时间"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="innerVisible = true">打开内层 Dialog</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>



<script>
// 富文本编辑器工具栏配置，因为涉及到富文本编辑器以外的组件调用，所以在这里我们需要重新自定义一下富文本编辑器的工具栏
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // toggled buttons
  ["blockquote", "code-block"],

  [
    {
      header: 1,
    },
    {
      header: 2,
    },
  ], // custom button values
  [
    {
      list: "ordered",
    },
    {
      list: "bullet",
    },
  ],
  [
    {
      script: "sub",
    },
    {
      script: "super",
    },
  ], // superscript/subscript
  [
    {
      indent: "-1",
    },
    {
      indent: "+1",
    },
  ], // outdent/indent
  [
    {
      direction: "rtl",
    },
  ], // text direction

  [
    {
      size: ["small", false, "large", "huge"],
    },
  ], // custom dropdown
  [
    {
      header: [1, 2, 3, 4, 5, 6, false],
    },
  ],

  [
    {
      color: [],
    },
    {
      background: [],
    },
  ], // dropdown with defaults from theme
  [
    {
      font: [],
    },
  ],
  [
    {
      align: [],
    },
  ],
  ["link", "image", "video"],
  ["clean"], // remove formatting button
];
export default {
  data() {
    return {
      visible: false,
      innerVisible: false,
      imgUploadUrl: "http://localhost:8080/renren-fast/uploadImgFile",
      token: "",
      // 富文本编辑器工具栏
      editorOption: {
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: {
              image: function (value) {
                if (value) {
                  // 调用element的图片上传组件
                  // （这里是用的原生js的选择dom方法）
                  document.querySelector("#upimg button").click();
                } else {
                  this.quill.format("image", false);
                }
              },
            },
          },
        },
      },
      dataForm: {
        id: 0,
        userId: "",
        type: "",
        title: "",
        content: "",
        isReaded: "",
        status: "",
        createBy: "",
        updateBy: "",
        createDate: "",
        updateDate: "",
        version: "",
        isDelete: "",
      },
      dataRule: {
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" },
        ],
        type: [
          {
            required: true,
            message: "消息类型(1平台公共消息,2指定用户消息)不能为空",
            trigger: "blur",
          },
        ],
        title: [
          { required: true, message: "消息标题不能为空", trigger: "blur" },
        ],
        content: [
          {
            required: true,
            message: "消息内容，富文本不能为空",
            trigger: "blur",
          },
        ],
        isReaded: [
          {
            required: true,
            message: "是否已读(0未读,1已读)不能为空",
            trigger: "blur",
          },
        ],
        status: [
          {
            required: true,
            message: "业务状态(1启用,2禁用)不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    handleSuccess(res) {
      // 获取富文本组件实例
      console.log(res);
      let quill = this.$refs.QuillEditor.quill;
      if (res.code == 0) {
        // 如果上传成功
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片，res为服务器返回的图片链接地址
        quill.insertEmbed(length, "image", res.url);
        // 调整光标到最后
        quill.setSelection(length + 1);
      } else {
        // 提示信息
        this.$message.error("图片插入失败");
      }
    },
    init(id) {
      this.dataForm.id = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(
              `/message/message/info/${this.dataForm.id}`
            ),
            method: "get",
            params: this.$http.adornParams(),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.userId = data.message.userId;
              this.dataForm.type = data.message.type + "";
              this.dataForm.title = data.message.title;
              this.dataForm.content = data.message.content;
              this.dataForm.isReaded = data.message.isReaded;
              this.dataForm.status = data.message.status + "";
              this.dataForm.createBy = data.message.createBy;
              this.dataForm.updateBy = data.message.updateBy;
              this.dataForm.createDate = data.message.createDate;
              this.dataForm.updateDate = data.message.updateDate;
              this.dataForm.version = data.message.version;
              this.dataForm.isDelete = data.message.isDelete;
            }
          });
        }
      });
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/message/message/${!this.dataForm.id ? "save" : "update"}`
            ),
            method: "post",
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              userId: this.dataForm.userId,
              type: this.dataForm.type,
              title: this.dataForm.title,
              content: this.dataForm.content,
              isReaded: this.dataForm.isReaded,
              status: this.dataForm.status,
              createBy: this.dataForm.createBy,
              updateBy: this.dataForm.updateBy,
              createDate: this.dataForm.createDate,
              updateDate: this.dataForm.updateDate,
              version: this.dataForm.version,
              isDelete: this.dataForm.isDelete,
            }),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
  },
};
</script>
